package com.xhtech.base.service.user.monitor

import androidx.lifecycle.LifecycleOwner
import com.xhtech.base.data.UserInfo
import com.xhtech.base.service.user.UserInfoManager
import com.yxh.lib_base.ext.viewbinding.ext.addObserver
import com.yxh.lib_base.ext.viewbinding.ext.addObserverDestroyed
import com.yxh.lib_base.util.LogUtils

/**
 * @author yuanxh
 * @date :2023/6/30 12:40
 * @description:
 */
class UserMonitorHelp : IUserMonitorListener {
    private val TAG = "UserMonitorHelp"
    private val _listenerList = mutableSetOf<(UserInfo) -> Unit>()

    override fun registerUserInfoChangeListener(
        lifecycle: LifecycleOwner,
        listener: (UserInfo) -> Unit
    ) {
        if (_listenerList.contains(listener)) return
        _listenerList.add(listener)
        UserInfoManager.getInstances().getUserInfo()?.let(listener)
        lifecycle.lifecycle.addObserver(destroyed = {
            _listenerList.remove(listener)
        })
    }

    override fun notifyDataChanged() {
        LogUtils.d(TAG, "notifyDataChanged listSize=${_listenerList.size}")
        UserInfoManager.getInstances().getUserInfo()?.let { userInfo ->
            _listenerList.forEach {
                it.invoke(userInfo)
            }
        }
    }
}